package com.kaifamiao.generic;

import java.util.Collection;
import java.util.Iterator;

/**
 * 类型参数 
 * 1、对于Bag类实现的Collection接口来说，其中的 X 是个实参 
 * 2、对于Bag类来说，其中的 X 是个形参
 */
public class Bag<X> implements Collection<X> {
	
	// 约定默认容量
	private static final int DEFAULT_CAPACITY = 10 ;
	// 约定默认加载因子
	private static final float DEFAULT_LOAD_FACTOR = 0.75F ;
	// 用来存放元素的数组
	private Object[] elements ;
	// 用来记录集合中所存放的元素个数
	private int counter ;
	// 加载因子(用于确定什么时候对elements数组扩容)
	private float loadFactor ;
	
	public Bag() {
		this( DEFAULT_CAPACITY , DEFAULT_LOAD_FACTOR );
	}
	
	public Bag( int initialCapacity ) {
		this( initialCapacity , DEFAULT_LOAD_FACTOR );
	}
	
	public Bag( int initialCapacity , float loadFactor ) {
		super();
		if( initialCapacity < 0 ) {
			throw new IllegalArgumentException( "集合容量必须大于零" );
		}
		if( loadFactor <= 0 || loadFactor >= 1 ) {
			throw new IllegalArgumentException( "加载因子必须是0到1之间的浮点数" );
		}
		// 根据指定的初始容量来创建数组对象
		this.elements = new Object[ initialCapacity ];
		// 根据参数设置加载因子
		this.loadFactor = loadFactor ;
	}

	// 用于对数组扩容的方法
	private void ensureCapacity() {
		// 确定是否需要扩容
		if (counter >= elements.length * loadFactor) {
			Object[] temp = elements;// 用临时变量缓存原数组
			int newLength = temp.length * 3 / 2 + 1;
			elements = new Object[newLength]; // 创建新数组
			// 将 temp 数组中 [ 0 , counter ) 之间的元素复制到 elements 数组中
			System.arraycopy(temp, 0, elements, 0, counter);
		}
	}

	@Override
	public boolean add(X e) {
		ensureCapacity();
		elements[counter++] = e;
		return true;
	}

	@Override
	public int size() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	@Override
	public boolean contains(Object o) {
		return false;
	}

	@Override
	public Iterator<X> iterator() {
		return null;
	}

	@Override
	public Object[] toArray() {
		return null;
	}

	@Override
	public <T> T[] toArray(T[] a) {
		return null;
	}

	@Override
	public boolean remove(Object o) {
		return false;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return false;
	}

	@Override
	public boolean addAll(Collection<? extends X> c) {
		return false;
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return false;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return false;
	}

	@Override
	public void clear() {
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append( '[' );
		for( int i = 0 ; i < counter ; i++ ) {
			Object e = elements[ i ];
			sb.append( e );
			sb.append( ',' );
		}
		int last = sb.lastIndexOf( "," );
		if( last != -1 ) {
			sb.deleteCharAt( last );
		}
		sb.append( ']' );
		return sb.toString();
	}

}
